import { useState, useEffect } from 'react';
import {
  Form,
  Input,
  Button,
  Card,
  Space,
  notification,
  Divider,
  Alert,
  Row,
  Col,
  Spin,
  Tag,
  Typography
} from 'antd';
import { 
  CheckCircleOutlined, 
  CloseCircleOutlined, 
  LoadingOutlined,
  KeyOutlined,
  ApiOutlined,
  RobotOutlined
} from '@ant-design/icons';
import axios from 'axios';

const { Text, Title } = Typography;

interface ModelConfigProps {
  onSaved?: () => void;
}

interface ConfigData {
  llm_model: string;
  llm_api_key: string;
  llm_base_url: string;
  embedding_model: string;
  embedding_api_key: string;
  embedding_base_url: string;
  embedding_batch_size: number;
}

interface TestStatus {
  llm: 'idle' | 'testing' | 'success' | 'error';
  embedding: 'idle' | 'testing' | 'success' | 'error';
  llmError?: string;
  embeddingError?: string;
}

const API_BASE_URL = 'http://127.0.0.1:5001';

const ModelConfig: React.FC<ModelConfigProps> = ({ onSaved }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [testStatus, setTestStatus] = useState<TestStatus>({
    llm: 'idle',
    embedding: 'idle'
  });

  // 默认配置
  const defaultConfig: ConfigData = {
    llm_model: 'qwen3-max-2025-09-23',
    llm_api_key: '',
    llm_base_url: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    embedding_model: 'text-embedding-v4',
    embedding_api_key: '',
    embedding_base_url: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    embedding_batch_size: 10
  };

  // 加载保存的配置
  useEffect(() => {
    const savedConfig = localStorage.getItem('modelConfig');
    if (savedConfig) {
      try {
        const config = JSON.parse(savedConfig);
        form.setFieldsValue({ ...defaultConfig, ...config });
      } catch (error) {
        console.error('加载配置失败:', error);
        form.setFieldsValue(defaultConfig);
      }
    } else {
      form.setFieldsValue(defaultConfig);
    }
  }, [form]);

  // 测试LLM连接
  const testLLMConnection = async (values: ConfigData) => {
    setTestStatus(prev => ({ ...prev, llm: 'testing', llmError: undefined }));
    
    try {
      await axios.post(`${API_BASE_URL}/health/llm`, {
        model: values.llm_model,
        api_key: values.llm_api_key,
        base_url: values.llm_base_url
      }, { timeout: 30000 });
      
      setTestStatus(prev => ({ ...prev, llm: 'success' }));
      notification.success({
        message: 'LLM连接测试成功',
        description: `模型 ${values.llm_model} 连接正常`
      });
    } catch (error: any) {
      const errorMsg = error.response?.data?.error || error.message || '连接失败';
      setTestStatus(prev => ({ ...prev, llm: 'error', llmError: errorMsg }));
      notification.error({
        message: 'LLM连接测试失败',
        description: errorMsg
      });
    }
  };

  // 测试嵌入模型连接
  const testEmbeddingConnection = async (values: ConfigData) => {
    setTestStatus(prev => ({ ...prev, embedding: 'testing', embeddingError: undefined }));
    
    try {
      await axios.post(`${API_BASE_URL}/health/embedding`, {
        model: values.embedding_model,
        api_key: values.embedding_api_key || values.llm_api_key,
        base_url: values.embedding_base_url || values.llm_base_url
      }, { timeout: 30000 });
      
      setTestStatus(prev => ({ ...prev, embedding: 'success' }));
      notification.success({
        message: '嵌入模型连接测试成功',
        description: `模型 ${values.embedding_model} 连接正常`
      });
    } catch (error: any) {
      const errorMsg = error.response?.data?.error || error.message || '连接失败';
      setTestStatus(prev => ({ ...prev, embedding: 'error', embeddingError: errorMsg }));
      notification.error({
        message: '嵌入模型连接测试失败',
        description: errorMsg
      });
    }
  };

  // 保存配置
  const handleSave = async (values: ConfigData) => {
    setLoading(true);
    
    try {
      // 保存到本地存储
      localStorage.setItem('modelConfig', JSON.stringify(values));
      
      // 发送到后端
      await axios.post(`${API_BASE_URL}/config`, values);
      
      notification.success({
        message: '配置保存成功',
        description: '模型配置已更新并生效'
      });
      
      onSaved?.();
    } catch (error: any) {
      const errorMsg = error.response?.data?.error || error.message;
      notification.error({
        message: '保存配置失败',
        description: errorMsg
      });
    } finally {
      setLoading(false);
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: string, error?: string) => {
    switch (status) {
      case 'testing':
        return <LoadingOutlined style={{ color: '#1890ff' }} />;
      case 'success':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'error':
        return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
      default:
        return null;
    }
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSave}
        autoComplete="off"
      >
        {/* LLM模型配置 */}
        <Card 
          title={
            <Space>
              <RobotOutlined />
              <span>LLM模型配置</span>
              {getStatusIcon(testStatus.llm)}
            </Space>
          }
          size="small"
          style={{ marginBottom: 16 }}
        >
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                label="API Key"
                name="llm_api_key"
                rules={[{ required: true, message: '请输入API Key' }]}
              >
                <Input.Password
                  prefix={<KeyOutlined />}
                  placeholder="请输入DashScope API Key"
                  size="large"
                />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="模型名称"
                name="llm_model"
                rules={[{ required: true, message: '请输入模型名称' }]}
              >
                <Input
                  placeholder="qwen3-max-2025-09-23"
                  size="large"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="API地址"
                name="llm_base_url"
                rules={[{ required: true, message: '请输入API地址' }]}
              >
                <Input
                  prefix={<ApiOutlined />}
                  placeholder="https://dashscope.aliyuncs.com/compatible-mode/v1"
                  size="large"
                />
              </Form.Item>
            </Col>
          </Row>

          {testStatus.llmError && (
            <Alert
              message="连接测试失败"
              description={testStatus.llmError}
              type="error"
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          <Button
            type="dashed"
            onClick={() => {
              form.validateFields(['llm_model', 'llm_api_key', 'llm_base_url'])
                .then(values => testLLMConnection(values as ConfigData))
                .catch(() => notification.warning({ message: '请先填写完整的LLM配置' }));
            }}
            loading={testStatus.llm === 'testing'}
            style={{ width: '100%' }}
          >
            测试LLM连接
          </Button>
        </Card>

        {/* 嵌入模型配置 */}
        <Card 
          title={
            <Space>
              <ApiOutlined />
              <span>嵌入模型配置</span>
              {getStatusIcon(testStatus.embedding)}
            </Space>
          }
          size="small"
          style={{ marginBottom: 16 }}
        >
          <Alert
            message="提示"
            description="如果嵌入模型使用相同的API Key和地址，可以留空自动使用LLM配置"
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="模型名称"
                name="embedding_model"
                rules={[{ required: true, message: '请输入嵌入模型名称' }]}
              >
                <Input
                  placeholder="text-embedding-v4"
                  size="large"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="批处理大小"
                name="embedding_batch_size"
                rules={[{ required: true, message: '请输入批处理大小' }]}
              >
                <Input
                  type="number"
                  placeholder="10"
                  size="large"
                  addonAfter="条/批"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="API Key (可选)"
                name="embedding_api_key"
              >
                <Input.Password
                  prefix={<KeyOutlined />}
                  placeholder="留空使用LLM的API Key"
                  size="large"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="API地址 (可选)"
                name="embedding_base_url"
              >
                <Input
                  prefix={<ApiOutlined />}
                  placeholder="留空使用LLM的API地址"
                  size="large"
                />
              </Form.Item>
            </Col>
          </Row>

          {testStatus.embeddingError && (
            <Alert
              message="连接测试失败"
              description={testStatus.embeddingError}
              type="error"
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          <Button
            type="dashed"
            onClick={() => {
              const values = form.getFieldsValue();
              testEmbeddingConnection(values as ConfigData);
            }}
            loading={testStatus.embedding === 'testing'}
            style={{ width: '100%' }}
          >
            测试嵌入模型连接
          </Button>
        </Card>

        {/* 推荐配置 */}
        <Card title="推荐配置" size="small" style={{ marginBottom: 24 }}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div>
              <Text strong>推荐LLM模型:</Text>
              <div style={{ marginTop: 8 }}>
                <Tag color="blue">qwen3-max-2025-09-23</Tag>
                <Tag color="green">deepseek-v3.1</Tag>
                <Tag color="orange">qwen-plus-2025-04-28</Tag>
              </div>
            </div>
            
            <div>
              <Text strong>推荐嵌入模型:</Text>
              <div style={{ marginTop: 8 }}>
                <Tag color="blue">text-embedding-v4</Tag>
                <Tag color="green">text-embedding-v3</Tag>
              </div>
            </div>

            <div>
              <Text strong>批处理大小建议:</Text>
              <div style={{ marginTop: 8 }}>
                <Text type="secondary">
                  text-embedding-v4: 建议10条/批 | text-embedding-v3: 建议25条/批
                </Text>
              </div>
            </div>
          </Space>
        </Card>

        <Divider />

        {/* 操作按钮 */}
        <Row gutter={16}>
          <Col span={12}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              size="large"
              style={{ width: '100%' }}
            >
              保存配置
            </Button>
          </Col>
          <Col span={12}>
            <Button
              onClick={() => {
                form.setFieldsValue(defaultConfig);
                setTestStatus({ llm: 'idle', embedding: 'idle' });
              }}
              size="large"
              style={{ width: '100%' }}
            >
              重置为默认
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default ModelConfig;
